package com.badboy.servlet;

import com.alibaba.fastjson2.JSON;
import com.badboy.mapper.PostManagementMapper;
import com.badboy.util.FastJsonUtil;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 33314
 * @version 1.0
 * @description: TODO
 * @date 2025/5/12 15:44
 */
@WebServlet("/CommentServlet")
public class CommentServlet extends HttpServlet {
    private SqlSessionFactory sqlSessionFactory;

    @Override
    public void init() throws ServletException {
        String resource = "mybatis-config.xml";
        try (InputStream inputStream = Resources.getResourceAsStream(resource)) {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            throw new ServletException("初始化 MyBatis 失败", e);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        String action = request.getParameter("action");
        if ("getCommentCount".equals(action)) {
            Long postId = Long.valueOf(request.getParameter("postId"));

            try (SqlSession session = sqlSessionFactory.openSession()) {
                PostManagementMapper mapper = session.getMapper(PostManagementMapper.class);
                Integer commentCount = mapper.selectCommentCountByPostId(postId);

                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("data", commentCount != null ? commentCount : 0);

                response.setContentType("application/json");
                response.getWriter().write(FastJsonUtil.toJSONString(result));
            }
        }
    }
}

